package com.android.vgongyi.common;

import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.vgongyi.R;
import com.android.vgongyi.entity.CommentEntity;
import com.android.vgongyi.utils.AsyncImageLoader;
import com.android.vgongyi.utils.AsyncImageLoader.ImageCallback;

public class CommentAdapter extends BaseAdapter {
	private Context context;
	private List<CommentEntity> list;
	private HashMap<Integer, View> viewCache;
	private AsyncImageLoader asyncImageLoader;
	private ListView listView;

	public CommentAdapter(Context context, List<CommentEntity> list,ListView listView) {
		this.context 		= context;
		this.list 			= list;
		this.listView		= listView;
		asyncImageLoader 	= new AsyncImageLoader();
		viewCache 			= new HashMap<Integer, View>();
	}

	public int getCount() {
		return list.size();
	}

	public Object getItem(int position) {
		return list.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View view = viewCache.get(position);
		if (view == null) {
			
			LayoutInflater inflater = LayoutInflater.from(context);
			view = inflater.inflate(R.layout.item_check_comment, null);
			
			ImageView userImg = (ImageView) view.findViewById(R.id.user_img);
			TextView userName = (TextView) view.findViewById(R.id.username);
			TextView contents = (TextView) view.findViewById(R.id.content);
			try{
				String imageUrl = list.get(position).getProfile_imageurl();
				userImg.setTag(imageUrl);
			
			Drawable cachedImage = asyncImageLoader.loadDrawable(context,position, imageUrl,"", new ImageCallback() {
						public void imageLoaded(Drawable imageDrawable,String imageUrl,String img_extension) {
							ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
							if (imageViewByTag != null && imageDrawable != null) {
								imageViewByTag.setImageDrawable(imageDrawable);
							}
						}});
			
			if (cachedImage == null) {
				userImg.setImageResource(R.drawable.icon);
			} else {
				userImg.setImageDrawable(cachedImage);
			}
			
			userName.setText(list.get(position).getWeibo_name());
			contents.setText(list.get(position).getComment_text());
			}catch (Exception e) {
			}
		}
		return view;
	}

}
